import React, { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import doctorService from '../services/doctorService';
import departmentService from '../services/departmentService';
import './FormStyles.css';

// 模拟数据，当API调用失败时使用
const MOCK_DOCTOR_DATA = {
    id: 1,
    user: {
        id: 2,
        username: 'doctest',
        fullName: '张医生',
        email: 'doctest@example.com',
        phoneNumber: '13800138000',
    },
    specialization: '心血管内科',
    departmentId: 1,
    departmentName: '内科',
    licenseNumber: 'DOC20211234',
    bio: '张医生是一位经验丰富的心血管专家，有十年临床经验。',
    availableSlots: '周一上午9:00-11:30,周三下午14:00-16:30',
};

const MOCK_DEPARTMENTS = [
    { id: 1, name: '内科' },
    { id: 2, name: '外科' },
    { id: 3, name: '妇产科' },
    { id: 4, name: '儿科' },
    { id: 5, name: '神经科' }
];

const DoctorProfilePage = () => {
    const [doctor, setDoctor] = useState({
        id: '',
        user: {
            id: '',
            username: '',
            fullName: '',
            email: '',
            phoneNumber: '',
        },
        specialization: '',
        departmentId: '',
        licenseNumber: '',
        bio: '',
        availableSlots: '',
    });

    const [departments, setDepartments] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [useMockData, setUseMockData] = useState(false);

    useEffect(() => {
        const fetchDoctorProfile = async () => {
            try {
                const response = await doctorService.getDoctorProfile();
                setDoctor(response.data);
                setLoading(false);
            } catch (err) {
                console.error('获取医生信息失败:', err);
                // 使用模拟数据
                setDoctor(MOCK_DOCTOR_DATA);
                setUseMockData(true);
                setLoading(false);
                toast.warning('使用模拟数据显示，实际API调用失败');
            }
        };

        const fetchDepartments = async () => {
            try {
                const response = await departmentService.getAllDepartments();
                setDepartments(response.data || []);
            } catch (err) {
                console.error('获取科室列表失败:', err);
                // 使用模拟科室数据
                setDepartments(MOCK_DEPARTMENTS);
            }
        };

        fetchDoctorProfile();
        fetchDepartments();
    }, []);

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        
        if (name.includes('.')) {
            const [parent, child] = name.split('.');
            setDoctor({
                ...doctor,
                [parent]: {
                    ...doctor[parent],
                    [child]: value
                }
            });
        } else {
            setDoctor({
                ...doctor,
                [name]: value
            });
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (useMockData) {
            // 如果使用的是模拟数据，则只显示成功消息，不实际提交
            toast.success('（模拟）个人信息更新成功');
            setIsEditing(false);
            return;
        }
        
        try {
            await doctorService.updateDoctorProfile(doctor);
            toast.success('个人信息更新成功');
            setIsEditing(false);
        } catch (err) {
            console.error('更新医生信息失败:', err);
            toast.error('更新失败，请稍后再试');
        }
    };

    if (loading) {
        return <div className="loading">加载中...</div>;
    }

    if (error && !useMockData) {
        return <div className="error">{error}</div>;
    }

    // 确保departments永远是数组
    const departmentOptions = Array.isArray(departments) ? departments : [];

    return (
        <div className="page-container">
            <h2>医生个人资料</h2>
            
            {useMockData && (
                <div className="warning-box">
                    <p>注意：当前显示的是模拟数据，后端API调用失败</p>
                </div>
            )}
            
            <div className="card">
                <div className="card-header">
                    <h3>基本信息</h3>
                    {!isEditing && (
                        <button className="btn-edit" onClick={() => setIsEditing(true)}>
                            编辑
                        </button>
                    )}
                </div>
                
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label>用户名</label>
                        <input
                            type="text"
                            name="user.username"
                            value={doctor.user?.username || ''}
                            onChange={handleInputChange}
                            disabled={true}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>姓名</label>
                        <input
                            type="text"
                            name="user.fullName"
                            value={doctor.user?.fullName || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>邮箱</label>
                        <input
                            type="email"
                            name="user.email"
                            value={doctor.user?.email || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>电话</label>
                        <input
                            type="text"
                            name="user.phoneNumber"
                            value={doctor.user?.phoneNumber || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>专业领域</label>
                        <input
                            type="text"
                            name="specialization"
                            value={doctor.specialization || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>所属科室</label>
                        <select
                            name="departmentId"
                            value={doctor.departmentId || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        >
                            <option value="">选择科室</option>
                            {departmentOptions.map(dept => (
                                <option key={dept.id} value={dept.id}>
                                    {dept.name}
                                </option>
                            ))}
                        </select>
                    </div>
                    
                    <div className="form-group">
                        <label>执业证号</label>
                        <input
                            type="text"
                            name="licenseNumber"
                            value={doctor.licenseNumber || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>个人简介</label>
                        <textarea
                            name="bio"
                            value={doctor.bio || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                            rows={5}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label>可预约时间段</label>
                        <textarea
                            name="availableSlots"
                            value={doctor.availableSlots || ''}
                            onChange={handleInputChange}
                            disabled={!isEditing}
                            rows={3}
                            placeholder="示例: 周一上午9:00-11:30,周三下午14:00-16:30"
                        />
                    </div>
                    
                    {isEditing && (
                        <div className="button-group">
                            <button type="submit" className="btn-primary">
                                保存
                            </button>
                            <button 
                                type="button" 
                                className="btn-secondary"
                                onClick={() => setIsEditing(false)}
                            >
                                取消
                            </button>
                        </div>
                    )}
                </form>
            </div>
        </div>
    );
};

export default DoctorProfilePage; 